from flask import Flask, redirect, request, Response
import requests
import os
basedir = os.path.abspath(os.path.dirname(__file__)) # 脚本当前路径
static_folder = os.path.join(basedir, "static")
app = Flask(__name__, static_folder=static_folder, static_url_path='/')

# 初始化代理：将/api请求转发到后端
API_BASE_URL="http://qsont.xyz:8016/api"

@app.route('/', methods=['GET'])
def index():
    return redirect('/index.html')

# 代理 API 路径，示例使用通配符捕获其余路径
@app.route('/api/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])
def proxy(path):
    # 构造目标URL
    url = f"{API_BASE_URL}/{path}"

    # 保持请求方法、参数、头部、数据
    method = request.method
    headers = {key: value for key, value in request.headers if key.lower() != 'host'}  # 不传 host 头
    params = request.args  # URL 查询参数
    data = request.get_data()  # 请求体（raw data）

    # 转发请求
    resp = requests.request(method, url, headers=headers, params=params, data=data, cookies=request.cookies, allow_redirects=False)

    # 过滤响应头，剔除对前端不适合的头，比如 Transfer-Encoding
    excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
    response_headers = [(name, value) for name, value in resp.raw.headers.items() if name.lower() not in excluded_headers]

    # 返回响应
    return Response(resp.content, resp.status_code, response_headers)

######################
if __name__ == '__main__':
    crt = os.path.join(basedir, '../crt/qsont.xyz.crt') 
    key = os.path.join(basedir, '../crt/qsont.xyz.key') 
    app.run(
        host="0.0.0.0",
        port=80,
        #ssl_context=(crt, key),
        debug=True
    )
